from rest_framework import serializers
from django_redis import get_redis_connection
from redis.exceptions import RedisError
import logging

logger = logging.getLogger('meiduo')


class RegisterSMSCodeSerializer(serializers.Serializer):
    text = serializers.CharField(max_length=4, min_length=4, label='用户输入的验证码', required=True)
    image_code_id = serializers.UUIDField(label='验证码唯一性id')

    def validate(self, attrs):

        # 获取用户输入的验证码
        text = attrs['text']
        image_code_id = attrs['image_code_id']

        # 连接ridis
        redis_conn = get_redis_connection('code')
        redis_text = redis_conn.get('img_%s' % image_code_id)
        # 判断验证马是否存在
        if redis_conn is None:
            raise serializers.ValidationError("验证码已过期")
        try:
            redis_conn.delete('img_%s' % image_code_id)

        except Exception as e:
            logger.log(e)

        if redis_text.decode().lower() != text.lower():
            raise serializers.ValidationError("验证码错误")

        return attrs
